package com.breaker.kata.leetcode;

public class MyAtoi {

    //ERROR
    public int myAtoi(String s) {
        String symbol = "";
        int result = 0;
        boolean start = false;
        for (Character character : s.trim().toCharArray()) {
            if (character.equals('-') || character.equals('+')) {
                if (start) {
                    return result;
                }
                symbol = character.toString();
                start = true;
                continue;
            }
            if (!Character.isDigit(character)) {
                if (isOverflow(result)) {
                    return convertValue(result, symbol, true);
                }
                return convertValue(result, symbol, false);
            }
            if (isOverflow(result)) {
                return convertValue(result, symbol, true);
            }
            result = result * 10 + Integer.parseInt(character.toString());
            start = true;
        }
        return convertValue(result, symbol, false);
    }

    private boolean isOverflow(int result) {
        return Integer.MAX_VALUE / 10 < result;
    }

    private int convertValue(int result, String symbol, boolean isOverflow) {
        if (symbol.equals("-")) {
            if (isOverflow) {
                return Integer.MIN_VALUE;
            }
            return -1 * result;
        }
        if (isOverflow) {
            return Integer.MAX_VALUE;
        }
        return result;
    }
}
